//
//  CountDownLabel.swift
//  Pods
//
//  Created by eme on 2017/4/10.
//
//

import Foundation
import SnapKit
import RxSwift
import RickonCore

class CountDownLabel: UIView {
    ///显示天
    var day_Lb:UILabel!
    var day_unit_Lb:UILabel!
    ///显示小时
    var hour_Lb:UILabel!
    var hour_unit_Lb:UILabel!
    ///显示分钟
    var minute_Lb:UILabel!
    var minute_unit_Lb:UILabel!
    ///显示秒
    var second_Lb:UILabel!
    
    ///单位宽度
    var unit_Width:Int = 7
    
    var timer: DispatchSourceTimer!
    
    var timerInterval:TimeInterval = 0{
        didSet{
            self.fireWithTimeIntervar(self.timerInterval)
        }
    }

    func setupSubviews() {
        day_Lb = self.getShowCountDown_Lb()
        day_Lb.text = "0"
        self.addSubview(day_Lb)
        
        day_unit_Lb = UILabel()
        day_unit_Lb.textColor = UIColor(hex: "343434")
        day_unit_Lb.backgroundColor = UIColor.clear
        day_unit_Lb.font = UIFont(name: Theme.fontName, size: 14)
        day_unit_Lb.textAlignment = .center
        day_unit_Lb.text = "天"
        self.addSubview(day_unit_Lb)
        
        hour_Lb = self.getShowCountDown_Lb()
        hour_Lb.text = "00"
        self.addSubview(hour_Lb)
        
        hour_unit_Lb = self.getShowCountDown_Unit_Lb()
        self.addSubview(hour_unit_Lb)
        
        minute_Lb = self.getShowCountDown_Lb()
        minute_Lb.text = "00"
        self.addSubview(minute_Lb)
        
        minute_unit_Lb = self.getShowCountDown_Unit_Lb()
        self.addSubview(minute_unit_Lb)
        
        second_Lb = self.getShowCountDown_Lb()
        second_Lb.text = "00"
        self.addSubview(second_Lb)
        day_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(2)
            make.top.equalTo(2)
            make.width.equalTo(self.day_Lb.snp.height).offset(0)
        }
        day_unit_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.day_Lb.snp.trailing).offset(0)
            make.width.equalTo(16)
        }
        hour_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.day_unit_Lb.snp.trailing).offset(0)
            make.top.equalTo(2)
            make.width.equalTo(self.hour_Lb.snp.height).offset(0)
        }
        hour_unit_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.hour_Lb.snp.trailing).offset(0)
            make.width.equalTo(unit_Width)
        }
        minute_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.hour_unit_Lb.snp.trailing).offset(0)
            make.top.equalTo(2)
            make.width.equalTo(self.minute_Lb.snp.height).offset(0)
        }
        minute_unit_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.minute_Lb.snp.trailing).offset(0)
            make.width.equalTo(unit_Width)
        }
        second_Lb.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.minute_unit_Lb.snp.trailing).offset(0)
            make.top.equalTo(2)
            make.width.equalTo(self.second_Lb.snp.height).offset(0)
        }
        
    }
    
    override func awakeFromNib() {
        setupSubviews()
    }
    
    /**
     *  根据指定时间间隔开始倒计时
     */
    func fireWithTimeIntervar(_ timerInterval:TimeInterval) {
        resetTimer()
        var timeout = timerInterval; //倒计时时间
        timer = DispatchSource.makeTimerSource(queue: .main)
        timer?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.milliseconds(100))
        timer?.setEventHandler {[unowned self] _ in
            if timeout <= 0 {
                print("结束")
                self.timer?.cancel()
                DispatchQueue.main.async {
                    // 执行操作，例如更新倒计时按钮UI
                    self.day_Lb.text = "0"
                    self.hour_Lb.text = "00"
                    self.minute_Lb.text = "00"
                    self.second_Lb.text = "00"
                }
            } else {
                DispatchQueue.main.async {
                    // 执行操作，例如更新倒计时按钮UI
                    self.updateLabel(timeout: timeout)
                    timeout = timeout - 1
                }
            }
        
        }
        // 启动定时器
        timer?.resume()
    }
    ///更新label控件
    func updateLabel(timeout:TimeInterval) {
        // 执行操作，例如更新倒计时按钮UI
        let days = Int(timeout/(3600*24))
        if days == 0{
            self.day_Lb.text = "0"
        }
        let hours = Int((timeout - Double(days*24*3600))/3600)
        let minute = Int((timeout - Double(days*24*3600 + hours*3600))/60)
        let second = Int(timeout - Double(days*24*3600 + hours*3600 + minute*60))
        if days == 0{
            self.day_Lb.text = "0"
        }else{
            self.day_Lb.text = "\(days)"
        }
        if hours < 10{
            self.hour_Lb.text = "0\(hours)"
        }else{
            self.hour_Lb.text = "\(hours)"
        }
        if minute < 10{
            self.minute_Lb.text = "0\(minute)"
        }else{
            self.minute_Lb.text = "\(minute)"
        }
        if second < 10{
            self.second_Lb.text = "0\(second)"
        }else{
            self.second_Lb.text = "\(second)"
        }
    }
    ///重置倒计时
    func resetTimer() {
        if self.timer != nil {
            self.timer.cancel()
        }
    }
    
    /// 创建按钮显示
    func getShowCountDown_Lb() -> UILabel {
        let lb = UILabel()
        lb.textColor = UIColor(hex: "ffffff")
        lb.backgroundColor = UIColor(hex: "343434")
        lb.font = UIFont(name: Theme.fontName, size: 14)
        lb.changeBorderColor(UIColor.clear)
        lb.textAlignment = .center
        return lb
    }
    /// 创建按钮显示
    func getShowCountDown_Unit_Lb() -> UILabel {
        let lb = UILabel()
        lb.textColor = UIColor(hex: "343434")
        lb.backgroundColor = UIColor.clear
        lb.font = UIFont(name: Theme.fontName, size: 16)
        lb.textAlignment = .center
        lb.text = ":"
        return lb
    }

}
